#include "BorrowRecord.h"

BorrowRecord::BorrowRecord()
    : recordId(0), borrowDate(0), dueDate(0), returnDate(0),
    isReturned(false), fineAmount(0.0) {
}

BorrowRecord::BorrowRecord(int id, string bId, string rId, time_t borrow, time_t due)
    : recordId(id), bookId(bId), readerId(rId), borrowDate(borrow),
    dueDate(due), returnDate(0), isReturned(false), fineAmount(0.0) {
}

void BorrowRecord::displayInfo() const {
    cout << "记录号: " << recordId << endl;
    cout << "图书号: " << bookId << endl;
    cout << "读者号: " << readerId << endl;
    cout << "借阅日期: " << timeToString(borrowDate) << endl;
    cout << "应还日期: " << timeToString(dueDate) << endl;
    if (isReturned) {
        cout << "归还日期: " << timeToString(returnDate) << endl;
    }
    cout << "状态: " << (isReturned ? "已归还" : "未归还") << endl;
    if (fineAmount > 0) {
        cout << "罚款金额: " << fineAmount << "元" << endl;
    }
    if (!isReturned && getOverdueDays() > 0) {
        cout << "逾期天数: " << getOverdueDays() << "天" << endl;
        cout << "预计罚款: " << calculateFine() << "元" << endl;
    }
    cout << "----------------------------------------" << endl;
}

string BorrowRecord::toString() const {
    stringstream ss;
    ss << recordId << "|" << bookId << "|" << readerId << "|"
        << borrowDate << "|" << dueDate << "|" << returnDate << "|"
        << isReturned << "|" << fineAmount;
    return ss.str();
}

BorrowRecord BorrowRecord::fromString(const string& data) {
    stringstream ss(data);
    int recordId;
    string bookId, readerId;
    time_t borrowDate, dueDate, returnDate;
    bool isReturned;
    double fineAmount;

    ss >> recordId; ss.ignore();
    getline(ss, bookId, '|');
    getline(ss, readerId, '|');
    ss >> borrowDate; ss.ignore();
    ss >> dueDate; ss.ignore();
    ss >> returnDate; ss.ignore();
    ss >> isReturned; ss.ignore();
    ss >> fineAmount;

    BorrowRecord record(recordId, bookId, readerId, borrowDate, dueDate);
    record.setReturnDate(returnDate);
    record.setIsReturned(isReturned);
    record.setFineAmount(fineAmount);
    return record;
}

double BorrowRecord::calculateFine() const {
    if (isReturned) {
        return fineAmount;
    }

    time_t now = time(nullptr);
    if (now > dueDate) {
        int overdueDays = static_cast<int>((now - dueDate) / (60 * 60 * 24));
        return overdueDays * 0.5; // 每天0.5元罚款
    }
    return 0.0;
}

int BorrowRecord::getOverdueDays() const {
    time_t now = time(nullptr);
    if (now > dueDate) {
        int overdueDays = static_cast<int>((now - dueDate) / (60 * 60 * 24));
    }
    return 0;
}

string BorrowRecord::timeToString(time_t time) {
    if (time == 0) return "未设置";
    tm timeinfo;
    localtime_s(&timeinfo, &time);
    stringstream ss;
    ss << (timeinfo.tm_year + 1900) << "-"
        << (timeinfo.tm_mon + 1) << "-"
        << timeinfo.tm_mday << " "
        << timeinfo.tm_hour << ":"
        << timeinfo.tm_min << ":"
        << timeinfo.tm_sec;
    return ss.str();
}